<template>
  <div>
    <!------------------------面包屑--------------------------->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{path:'/blank'}"><i class="el-icon-guide" style="color: black"></i>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!-- 添加班级 -->
    <el-row style="text-align: left;margin: 10px 0">
      <el-button type="primary"
                 icon="el-icon-plus"
                 size="medium"
                 @click="$router.push('/class/add-new')">添加班级</el-button>
      <!-- -----------------------------下拉选-------------------------------->
      <el-select v-model="classId"
                 placeholder="输入班级名"
                  @change="selectByClassName"
                 style="display: inline-block;float: left;margin-right: 10px">
        <el-option
            v-for="(item,cIndex) in classNameArr"
            :key="cIndex"
            :label="item.className"
            :value="item.classId">
        </el-option>
      </el-select>
    </el-row>

    <!------------------------表格开始--------------------------->
    <el-table
        :data="ClassData"
        stripe
        border
        style="width: 100%">
      <el-table-column
          prop="id"
          label="班级ID"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="className"
          label="班级名称"
          header-align="center"
          align="center"
          show-overflow-tooltip
          width="150">
        <template slot-scope="scope">
          <!-- ---------------------------------------------------------------------------------------- -->
          <a style="text-decoration: none;color: #409EFF;cursor:pointer"
             @click="goToQuestion(scope.row.id)">
            {{ scope.row.className }}</a>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="gmtCreate"
          show-overflow-tooltip
          label="创建时间">
      </el-table-column>
      <el-table-column
          align="center"
          prop="gmtModified"
          show-overflow-tooltip
          label="修改时间">
      </el-table-column>
      <el-table-column
          label="操作"
          width="150"
          align="center">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" size="mini" type="primary" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button icon="el-icon-delete" size="mini" type="danger" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--  ------------------------分页器------------------------  -->
    <div style="text-align: right;margin-top: 10px">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>
    <!--    修改弹出框-->
    <div style="margin: 0 auto">
      <el-dialog title="修改班级" :visible.sync="dialogFormVisible" width="480px">
        <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px" style="margin: -10px 0 -28px 0">
          <el-form-item label="班级id" prop="id">
            <el-input v-model="editForm.id" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="editForm.className" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>


<script>
let localJwt = localStorage.getItem('localJwt');
export default {
  data() {
    return {
      ClassData: [],
      classId: '',
      classNameArr:[],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      majorId:0,
      rules: {
        className: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
        ],
        id: [
          {required: true, message: '请输入班级id', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]?)$/, message: "专业id必须在0~99之间", trigger: 'blur'}
        ]
      },
      //Dialog属性
      dialogFormVisible: false,
      editForm: {
        id: '',
        name: '',
      },
    }
  },
  methods: {
    /*跳转对应班级的试题管理*/
    goToQuestion(id) {
      let path = '/class/ClassDetails?classId=' + id;/*++++++++++++++++++++++++*/
      this.$router.push(path);
    },
    /*下拉选筛选 根据班级名（和专业id）*/
    selectByClassName(){
      // http://localhost:9284/class/list-select
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      console.log(this.majorId);
      console.log(this.classId);
      let selectClassParam = {classId:this.classId,majorId:this.majorId};
      let formData = this.qs.stringify(selectClassParam);
      let url = ' http://localhost:9284/class/list-select?page='+ page+"&"+formData;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult.state);
        console.log(jsonResult.data.list);
        if (jsonResult.state == 20000) {
          this.ClassData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确认',
            callback: action => {// eslint-disable-line no-unused-vars
            }
          })
        }
      });
    },
    /*加载下拉选*/
    loadOptions(){
      let url = 'http://localhost:9284/class/easy-classList?majorId=' + this.majorId;
      console.log('url =' + url);

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.classNameArr = jsonResult.data;
          console.log(this.classNameArr)
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确认',
            callback: action => {// eslint-disable-line no-unused-vars

            }
          })
        }
      });
    },
    openEditDialog(grade) {
      let url = 'http://localhost:9284/class/standard?id=' + grade.id;
      console.log('url =' + url);

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确认',
            callback: action => {// eslint-disable-line no-unused-vars

            }
          })
        }
      });
    },
    submitEditForm() {
      let url = 'http://localhost:9284/class/update';
      console.log('url=' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadclassList();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (jsonResult == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.dialogFormVisible = false;
              this.loadclassList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
            }
          });
        }
      });
    },
    openDeleteConfirm(grade) {
      this.$confirm('此操作将永久删除【' + grade.id + '-' + grade.className + '】班级，是否继续？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: "warning",
      }).then(() => {
        this.handleDelete(grade);
      }).catch(() => {
      });
    },
    handleDelete(grade) {
      let url = 'http://localhost:9284/class/' + grade.id + '/delete';
      console.log('url = ' + url);

      let formData = 'id=' + grade.id;
      console.log('formData = ' + formData);

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除班级成功！',
            type: 'success'
          });
          this.loadclassList();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
              this.loadclassList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {// eslint-disable-line no-unused-vars
            }
          });
        }
      });
    },
    changePage(value) {
      this.$router.replace('?page=' + value);
      if (this.classId!=null){
        this.selectByClassName();
      }else {
        this.loadclassList( this.majorId);
      }
    },
    loadclassList(majorId) {

      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      console.log('localJwt =' + localJwt);
      let url = 'http://localhost:9284/class/'+majorId+'/list?page=' + page;
      console.log('url =' + url);

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult.state);
        console.log(jsonResult.data.list);
        if (jsonResult.state == 20000) {
          this.ClassData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确认',
            callback: action => {// eslint-disable-line no-unused-vars
            }
          })
        }
      });
    },
  },
  mounted() {
    if (location.search.includes('majorId')){
      this.majorId = location.search.split('=')[1];
      console.log('majorId=' +  this.majorId);
      this.loadclassList(this.majorId);
    }else {
      this.loadclassList(this.majorId);
    }
    this.loadOptions();
  }
}
</script>

<style scoped>

</style>
